/*
 * crearAsiento.java
 *
 * Created on 7 de agosto de 2007, 10:58 AM
 */

package administrador;
import java.sql.*;
import java.util.Calendar;
import javax.swing.*;
/**
 *
 * @author  daniel1
 */
public class crearAsiento extends javax.swing.JFrame {
 Usuario user;
 int bodega;
 AdministradorDiario admind;
 Conexion conexion;
    /** Creates new form crearAsiento */
    public crearAsiento(Conexion cEnt,Usuario user,AdministradorDiario adEnt) {
        admind=adEnt;
        this.user=user;
        conexion=cEnt;
        initComponents();
        setVisible(true);
        setBounds(200,100,460,450);
        cargarDatos();
    }
    
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        txt_codigo = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        txt_fecha = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        txt_ref = new javax.swing.JTextArea();
        jScrollPane2 = new javax.swing.JScrollPane();
        tabla = new javax.swing.JTable();
        lbl_coddiario = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Creacion de Asientos"));
        jPanel1.setLayout(null);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14));
        jLabel1.setForeground(new java.awt.Color(204, 51, 0));
        jLabel1.setText("Creacion de Asientos:");
        jPanel1.add(jLabel1);
        jLabel1.setBounds(30, 30, 149, 17);

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel2.setText("Codigo:");
        jPanel1.add(jLabel2);
        jLabel2.setBounds(30, 60, 41, 14);

        txt_codigo.setEditable(false);
        jPanel1.add(txt_codigo);
        txt_codigo.setBounds(80, 60, 60, 20);

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel3.setText("Codigo de Diario:");
        jPanel1.add(jLabel3);
        jLabel3.setBounds(240, 70, 94, 14);

        jLabel4.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel4.setText("fecha:");
        jPanel1.add(jLabel4);
        jLabel4.setBounds(34, 80, 40, 20);

        jLabel5.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel5.setText("Referencia:");
        jPanel1.add(jLabel5);
        jLabel5.setBounds(30, 280, 64, 14);

        txt_fecha.setEditable(false);
        jPanel1.add(txt_fecha);
        txt_fecha.setBounds(80, 80, 90, 20);

        txt_ref.setColumns(20);
        txt_ref.setRows(5);
        jScrollPane1.setViewportView(txt_ref);

        jPanel1.add(jScrollPane1);
        jScrollPane1.setBounds(30, 300, 390, 70);

        tabla.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Codigo", "parcial", "debe", "haber"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jScrollPane2.setViewportView(tabla);

        jPanel1.add(jScrollPane2);
        jScrollPane2.setBounds(30, 120, 390, 150);

        lbl_coddiario.setFont(new java.awt.Font("Tahoma", 1, 12));
        jPanel1.add(lbl_coddiario);
        lbl_coddiario.setBounds(340, 60, 50, 30);

        jButton1.setText("Agregar Cuenta");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jPanel1.add(jButton1);
        jButton1.setBounds(235, 90, 180, 23);

        jButton2.setText("Crear Asiento");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jPanel1.add(jButton2);
        jButton2.setBounds(310, 380, 110, 23);

        getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
       registroAsiento(); 
       admind.refrescar();
       this.dispose();
    }//GEN-LAST:event_jButton2ActionPerformed
    public void registroAsiento(){
        
       //System.out.println("*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*");
        if(!txt_codigo.getText().equals("")){
            
            //inserto cabecera ;
            
            String fecha=new java.sql.Date(System.currentTimeMillis()).toString();
            String codigoAsiento=txt_codigo.getText();
            String cod_diario=lbl_coddiario.getText();
            String referencia=txt_ref.getText();
            
           //System.out.println("@@@ Ingreso la Asiento @@@");
            conexion.insertarDatos("insert into asiento values("+codigoAsiento+","+cod_diario+",'"+fecha+"','"+referencia+"')");
           //System.out.println("@@@FIN Ingreso la cabecera del asiento  @@@");
            //Inserto detalle ;
            
            int filas=tabla.getRowCount();
            //System.out.println("Las fila editadas son"+filas);
            int cont=0;
            
            while(cont<filas){
               //System.out.println("Comienza el while");
                try{
                    String codigoCuenta=tabla.getValueAt(cont,0).toString();
                   //System.out.println("El codigo es:"+codigoCuenta);
                    String niveles[]=codigoCuenta.split(",");
                   //System.out.println("El pn es:"+niveles[0]);
                   //System.out.println("El sn es:"+niveles[1]);
                   //System.out.println("El tn es:"+niveles[2]);
                    Object parcial=tabla.getValueAt(cont,1);
                    Object debe=tabla.getValueAt(cont,2);
                    Object haber=tabla.getValueAt(cont,3);
                    
                    if(parcial==null){
                    parcial="null";
                    }
                    if(debe==null){
                    debe="null";
                    }
                    if(haber==null){
                    haber="null";
                    }
                    
                   //System.out.println("El parcial es:"+parcial.toString());
                   //System.out.println("El debe es:"+debe.toString());
                   //System.out.println("El haber es:"+haber.toString());
                    
                    //Saco el ultimo detalle ingresado:
                    ResultSet resp=conexion.consultarBase("select MAX(cod_detalle) from dtl_asiento where cod_asiento="+codigoAsiento);
                    resp.beforeFirst();
                    resp.next();
                    int codigoDetalle=resp.getInt(1);
                    codigoDetalle++;
                    
                    
                        //En el caso de que no sea un Combo:
                       //System.out.println("@@@  Ingreso Detalle Factura ----- @@@");
                        conexion.insertarDatos("insert into dtl_asiento values("+lbl_coddiario.getText()+","+codigoAsiento+","+codigoDetalle+","+niveles[2]+","+niveles[1]+","+niveles[0]+","+parcial+","+debe+","+haber+")");
                       //System.out.println("@@@ FIN Ingreso Detalle Factura ----- @@@");
                        
                    
                }catch(Exception e){
                    System.err.println(e);
                }
                
                cont++;
            }
            
            limpiar();
            cargarDatos();
        }else{
            JOptionPane.showMessageDialog(this,"Complete todos los datos de la factura","Informacion",JOptionPane.INFORMATION_MESSAGE);
            
        }
        
        
        
        
    }
    
     public void limpiar(){
       
        //Limpio Tabla
        int filas=tabla.getRowCount();
        int cont=0;
        while(cont<filas){
            try{
                for(int i=0;i<5;i++){
                    //System.out.println("valor fila:"+cont+" columnas: "+i);
                    tabla.setValueAt(null,cont,i);
                    ////System.out.println(toma);
                }
            }catch(Exception e){};
            cont++;
        }
        //Limpio de texto
        txt_ref.setText("");

    }
    
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
        crearDetalle cd=new crearDetalle(conexion,user,this);
    }//GEN-LAST:event_jButton1ActionPerformed
    public void cargarDatos(){
    this.lbl_coddiario.setText(admind.cb_codigo.getItemAt(admind.cb_codigo.getSelectedIndex()).toString());
    
    String DATE_FORMAT = "yyyy-MM-dd";//Refer Java DOCS for formats
    java.text.SimpleDateFormat sdf =  new java.text.SimpleDateFormat(DATE_FORMAT);
    Calendar c1 = Calendar.getInstance();
    
    this.txt_fecha.setText(sdf.format(c1.getTime()));
    cargarCodigoAsiento();
    }
    
    public void cargarCodigoAsiento(){
    String codigo=lbl_coddiario.getText();
    ResultSet r=conexion.consultarBase("SELECT max(cod_asiento) FROM asiento where cod_diario="+codigo+";");
        try {
            r.beforeFirst();
            r.next();
            int numero=r.getInt(1);
            numero=numero+1;
            this.txt_codigo.setText(String.valueOf(numero));
        } catch (SQLException ex) {
            ex.printStackTrace();
            this.txt_codigo.setText("1");
        }
    
    
    }
    
    
    public int cuentaFilaOcupadas(){
       int totalfilas=tabla.getRowCount();
       int contador=0;
       Object valor;
       for (contador=0;contador<totalfilas;contador++)
       {
           valor=tabla.getValueAt(contador,0);
           if (valor==null){
            break;
           }
           
       }
       //System.out.println("El numero de fila ocupadas es:"+contador);
        return contador;
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel lbl_coddiario;
    public javax.swing.JTable tabla;
    private javax.swing.JTextField txt_codigo;
    private javax.swing.JTextField txt_fecha;
    private javax.swing.JTextArea txt_ref;
    // End of variables declaration//GEN-END:variables
    
}
